<template>
  <div class="profit-loss">
    <el-skeleton :rows="10" animated v-if="loading" />
    
    <template v-else>
      <!-- 损益概览卡片 -->
      <div class="metric-cards">
        <el-card class="metric-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总收入</span>
              <el-tag size="small" :type="revenueGrowth >= 0 ? 'success' : 'danger'">
                {{ revenueGrowth >= 0 ? '+' : '' }}{{ revenueGrowth }}%
              </el-tag>
            </div>
          </template>
          <div class="metric-value">¥{{ formatNumber(totalRevenue) }}</div>
          <div class="metric-compare">
            环比: ¥{{ lastPeriodRevenue ? formatNumber(lastPeriodRevenue) : '无数据' }}
          </div>
        </el-card>
        
        <el-card class="metric-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总成本</span>
              <el-tag size="small" :type="costGrowth <= 0 ? 'success' : 'danger'">
                {{ costGrowth >= 0 ? '+' : '' }}{{ costGrowth }}%
              </el-tag>
            </div>
          </template>
          <div class="metric-value">¥{{ formatNumber(totalCost) }}</div>
          <div class="metric-compare">
            环比: ¥{{ lastPeriodCost ? formatNumber(lastPeriodCost) : '无数据' }}
          </div>
        </el-card>
        
        <el-card class="metric-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总利润</span>
              <el-tag size="small" :type="profitGrowth >= 0 ? 'success' : 'danger'">
                {{ profitGrowth >= 0 ? '+' : '' }}{{ profitGrowth }}%
              </el-tag>
            </div>
          </template>
          <div class="metric-value">¥{{ formatNumber(totalProfit) }}</div>
          <div class="metric-compare">
            环比: ¥{{ lastPeriodProfit ? formatNumber(lastPeriodProfit) : '无数据' }}
          </div>
        </el-card>
        
        <el-card class="metric-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>利润率</span>
              <el-tag size="small" :type="profitMarginGrowth >= 0 ? 'success' : 'danger'">
                {{ profitMarginGrowth >= 0 ? '+' : '' }}{{ profitMarginGrowth }}%
              </el-tag>
            </div>
          </template>
          <div class="metric-value">{{ formatNumber(profitMargin) }}%</div>
          <div class="metric-compare">
            环比: {{ lastPeriodProfitMargin ? formatNumber(lastPeriodProfitMargin) : '无数据' }}%
          </div>
        </el-card>
      </div>
      
      <!-- 利润趋势图 -->
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>利润趋势分析</span>
            <div class="chart-controls">
              <el-radio-group v-model="trendTimeUnit" size="small" @change="updateTrendChart">
                <el-radio-button label="day">日</el-radio-button>
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </template>
        <div class="chart-container" ref="profitTrendChart"></div>
      </el-card>
      
      <!-- 收入和成本占比图 -->
      <div class="chart-row">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>收入构成</span>
            </div>
          </template>
          <div class="chart-container" ref="revenueCompositionChart"></div>
        </el-card>
        
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>成本构成</span>
            </div>
          </template>
          <div class="chart-container" ref="costCompositionChart"></div>
        </el-card>
      </div>
      
      <!-- 损益表详情 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>损益表详情</span>
            <div class="table-actions">
              <el-select v-model="periodType" placeholder="期间类型" @change="handlePeriodChange">
                <el-option label="日报表" value="daily" />
                <el-option label="周报表" value="weekly" />
                <el-option label="月报表" value="monthly" />
              </el-select>
              
              <el-button type="primary" @click="printProfitLossStatement">
                <el-icon><Printer /></el-icon> 打印报表
              </el-button>
            </div>
          </div>
        </template>
        
        <el-table :data="profitLossDetails" stripe style="width: 100%" :span-method="objectSpanMethod">
          <el-table-column prop="category" label="项目" min-width="180" />
          <el-table-column prop="subcategory" label="子项目" min-width="180" />
          <el-table-column prop="amount" label="金额" min-width="120">
            <template #default="scope">
              <span :class="{ 'negative-amount': scope.row.amount < 0 }">
                ¥{{ formatNumber(Math.abs(scope.row.amount)) }}
                <span v-if="scope.row.amount < 0">(-)</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="total" label="小计" min-width="120">
            <template #default="scope">
              <span v-if="scope.row.isSubtotal" :class="{ 'negative-amount': scope.row.total < 0, 'subtotal': true }">
                ¥{{ formatNumber(Math.abs(scope.row.total)) }}
                <span v-if="scope.row.total < 0">(-)</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="ratio" label="占比" min-width="100">
            <template #default="scope">
              <span v-if="scope.row.ratio !== undefined">{{ scope.row.ratio }}%</span>
            </template>
          </el-table-column>
          <el-table-column prop="comment" label="说明" min-width="200" />
        </el-table>
        
        <div class="summary-section">
          <div class="summary-item">
            <span class="summary-label">毛利润:</span>
            <span class="summary-value">¥{{ formatNumber(grossProfit) }}</span>
            <span class="summary-percentage">({{ grossProfitMargin }}%)</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">营业利润:</span>
            <span class="summary-value">¥{{ formatNumber(operatingProfit) }}</span>
            <span class="summary-percentage">({{ operatingProfitMargin }}%)</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">净利润:</span>
            <span class="summary-value">¥{{ formatNumber(netProfit) }}</span>
            <span class="summary-percentage">({{ netProfitMargin }}%)</span>
          </div>
        </div>
      </el-card>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { Printer } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts/core'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的组件
echarts.use([
  BarChart,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent,
  CanvasRenderer
])

const props = defineProps({
  dateRange: {
    type: Array,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  },
  reportData: {
    type: Object,
    default: () => ({})
  }
})

// 图表引用
const profitTrendChart = ref(null)
const revenueCompositionChart = ref(null)
const costCompositionChart = ref(null)

// 图表实例
let profitTrendChartInstance = null
let revenueCompositionChartInstance = null
let costCompositionChartInstance = null

// 控制变量
const trendTimeUnit = ref('day')
const periodType = ref('monthly')

// 计算属性 - 从报表数据中提取需要的数据
const totalRevenue = computed(() => props.reportData.totalRevenue || 0)
const totalCost = computed(() => props.reportData.totalCost || 0)
const totalProfit = computed(() => props.reportData.totalProfit || 0)
const profitMargin = computed(() => props.reportData.profitMargin || 0)
const revenueGrowth = computed(() => props.reportData.revenueGrowth || 0)
const costGrowth = computed(() => props.reportData.costGrowth || 0)
const profitGrowth = computed(() => props.reportData.profitGrowth || 0)
const profitMarginGrowth = computed(() => props.reportData.profitMarginGrowth || 0)
const lastPeriodRevenue = computed(() => props.reportData.lastPeriodRevenue || 0)
const lastPeriodCost = computed(() => props.reportData.lastPeriodCost || 0)
const lastPeriodProfit = computed(() => props.reportData.lastPeriodProfit || 0)
const lastPeriodProfitMargin = computed(() => props.reportData.lastPeriodProfitMargin || 0)
const grossProfit = computed(() => props.reportData.grossProfit || 0)
const grossProfitMargin = computed(() => props.reportData.grossProfitMargin || 0)
const operatingProfit = computed(() => props.reportData.operatingProfit || 0)
const operatingProfitMargin = computed(() => props.reportData.operatingProfitMargin || 0)
const netProfit = computed(() => props.reportData.netProfit || 0)
const netProfitMargin = computed(() => props.reportData.netProfitMargin || 0)

// 损益表详情
const profitLossDetails = computed(() => {
  const periodData = props.reportData.profitLossDetails || {}
  return periodData[periodType.value] || []
})

// 格式化数字函数
const formatNumber = (num) => {
  if (num === undefined || num === null) return '0'
  
  // 如果是整数，直接返回
  if (Number.isInteger(num)) return num.toString()
  
  // 否则保留两位小数
  return num.toFixed(2)
}

// 表格合并单元格方法
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 第一列（项目）合并行
  if (columnIndex === 0 && row.rowspan) {
    return {
      rowspan: row.rowspan,
      colspan: 1
    }
  }
  
  // 如果是合并行但不是第一行，则第一列不显示
  if (columnIndex === 0 && row.rowspan === 0) {
    return {
      rowspan: 0,
      colspan: 0
    }
  }
  
  // 小计列，只在特定行显示
  if (columnIndex === 3 && !row.isSubtotal) {
    return {
      rowspan: 0,
      colspan: 0
    }
  }
  
  return {
    rowspan: 1,
    colspan: 1
  }
}

// 初始化利润趋势图
const initProfitTrendChart = () => {
  if (!profitTrendChart.value) return
  
  // 如果图表已经存在，销毁它
  if (profitTrendChartInstance) {
    profitTrendChartInstance.dispose()
  }
  
  // 创建新的图表实例
  profitTrendChartInstance = echarts.init(profitTrendChart.value)
  
  // 获取数据
  const trendData = props.reportData.profitTrend || {}
  const trendUnit = trendTimeUnit.value
  const xAxisData = trendData[trendUnit]?.dates || []
  const revenueData = trendData[trendUnit]?.revenues || []
  const costData = trendData[trendUnit]?.costs || []
  const profitData = trendData[trendUnit]?.profits || []
  const profitMarginData = trendData[trendUnit]?.profitMargins || []
  
  // 图表配置
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['收入', '成本', '利润', '利润率']
    },
    grid: {
      left: '3%',
      right: '5%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: xAxisData,
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '金额',
        min: 0,
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      {
        type: 'value',
        name: '利润率',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '收入',
        type: 'bar',
        data: revenueData,
        barGap: 0
      },
      {
        name: '成本',
        type: 'bar',
        data: costData,
        barGap: 0
      },
      {
        name: '利润',
        type: 'line',
        data: profitData,
        lineStyle: {
          width: 3,
          color: '#67C23A'
        },
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '利润率',
        type: 'line',
        yAxisIndex: 1,
        data: profitMarginData,
        lineStyle: {
          width: 3,
          color: '#F56C6C'
        },
        itemStyle: {
          color: '#F56C6C'
        }
      }
    ]
  }
  
  // 设置图表配置
  profitTrendChartInstance.setOption(option)
  
  // 窗口大小变化时自动调整图表大小
  window.addEventListener('resize', () => {
    profitTrendChartInstance.resize()
  })
}

// 初始化收入构成图
const initRevenueCompositionChart = () => {
  if (!revenueCompositionChart.value) return
  
  // 如果图表已经存在，销毁它
  if (revenueCompositionChartInstance) {
    revenueCompositionChartInstance.dispose()
  }
  
  // 创建新的图表实例
  revenueCompositionChartInstance = echarts.init(revenueCompositionChart.value)
  
  // 获取数据
  const revenueData = props.reportData.revenueComposition || []
  
  // 将数据转换为饼图需要的格式
  const pieData = revenueData.map(item => ({
    name: item.name,
    value: item.amount
  }))
  
  // 图表配置
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: revenueData.map(item => item.name)
    },
    series: [
      {
        name: '收入来源',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: pieData
      }
    ]
  }
  
  // 设置图表配置
  revenueCompositionChartInstance.setOption(option)
  
  // 窗口大小变化时自动调整图表大小
  window.addEventListener('resize', () => {
    revenueCompositionChartInstance.resize()
  })
}

// 初始化成本构成图
const initCostCompositionChart = () => {
  if (!costCompositionChart.value) return
  
  // 如果图表已经存在，销毁它
  if (costCompositionChartInstance) {
    costCompositionChartInstance.dispose()
  }
  
  // 创建新的图表实例
  costCompositionChartInstance = echarts.init(costCompositionChart.value)
  
  // 获取数据
  const costData = props.reportData.costComposition || []
  
  // 将数据转换为饼图需要的格式
  const pieData = costData.map(item => ({
    name: item.name,
    value: item.amount
  }))
  
  // 图表配置
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: costData.map(item => item.name)
    },
    series: [
      {
        name: '成本类别',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: pieData
      }
    ]
  }
  
  // 设置图表配置
  costCompositionChartInstance.setOption(option)
  
  // 窗口大小变化时自动调整图表大小
  window.addEventListener('resize', () => {
    costCompositionChartInstance.resize()
  })
}

// 更新趋势图的时间单位
const updateTrendChart = () => {
  initProfitTrendChart()
}

// 处理期间类型变更
const handlePeriodChange = () => {
  // 仅更新表格数据，无需其他操作
}

// 打印损益表
const printProfitLossStatement = () => {
  ElMessage.success('损益表打印功能即将上线')
  // 这里可以添加打印报表的功能
}

// 监听数据变化，更新图表
watch(() => props.reportData, () => {
  nextTick(() => {
    initProfitTrendChart()
    initRevenueCompositionChart()
    initCostCompositionChart()
  })
}, { deep: true })

// 组件挂载时初始化图表
onMounted(() => {
  if (!props.loading && Object.keys(props.reportData).length > 0) {
    nextTick(() => {
      initProfitTrendChart()
      initRevenueCompositionChart()
      initCostCompositionChart()
    })
  }
})

// 组件卸载时清理图表实例
onUnmounted(() => {
  if (profitTrendChartInstance) {
    profitTrendChartInstance.dispose()
  }
  if (revenueCompositionChartInstance) {
    revenueCompositionChartInstance.dispose()
  }
  if (costCompositionChartInstance) {
    costCompositionChartInstance.dispose()
  }
  
  window.removeEventListener('resize', () => {
    if (profitTrendChartInstance) profitTrendChartInstance.resize()
    if (revenueCompositionChartInstance) revenueCompositionChartInstance.resize()
    if (costCompositionChartInstance) costCompositionChartInstance.resize()
  })
})
</script>

<style scoped>
.profit-loss {
  width: 100%;
}

.metric-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.metric-card {
  cursor: pointer;
  transition: all 0.3s;
}

.metric-card:hover {
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
}

.metric-compare {
  font-size: 14px;
  color: #909399;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 400px;
  width: 100%;
}

.chart-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-controls {
  display: flex;
  align-items: center;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.negative-amount {
  color: #F56C6C;
}

.subtotal {
  font-weight: bold;
}

.summary-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.summary-item {
  display: flex;
  margin-bottom: 10px;
}

.summary-item:last-child {
  margin-bottom: 0;
}

.summary-label {
  font-weight: bold;
  width: 100px;
}

.summary-value {
  font-weight: bold;
  margin-right: 10px;
}

.summary-percentage {
  color: #409EFF;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .metric-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .chart-row {
    grid-template-columns: 1fr;
  }
  
  .table-actions {
    flex-direction: column;
  }
}

@media (max-width: 768px) {
  .metric-cards {
    grid-template-columns: 1fr;
  }
}
</style>